package com.itheima.reggie.service.impl;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.domain.Dish;
import com.itheima.reggie.domain.DishFlavor;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishFlavorMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.vo.CustomException;
import com.itheima.reggie.vo.R;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private DishFlavorService dishFlavorService;

    /**
     * 添加菜品和菜品的口味
     *
     * @return
     */
    @Transactional
    @Override
    public R add(DishDto dto) {
        //1.校验参数
        if (dto == null) {
            return R.error("参数有误");
        }

        //2.添加菜品数据到dish表
        //手动生成雪花id
        long id = IdWorker.getId();
        dto.setId(id);
        //补全剩余数据
        dto.setSort(0);
        dto.setIsDeleted(0);
        dishMapper.insertDish(dto);

        //3.添加口味数据到数据库表中
        List<DishFlavor> flavors = dto.getFlavors();
        //填充口味数据
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(id);
        }
        //批量添加
        dishFlavorMapper.insertFlavor(flavors);

        return R.success("添加成功");
    }

    /**
     * 修改菜品回显功能
     */
    @Override
    public R findById(Long id) {
        Dish dish = this.getById(id);
        List<DishFlavor> flavors = dishFlavorService.list(Wrappers.lambdaQuery(DishFlavor.class)
                .eq(DishFlavor::getDishId, id));
        dish.setFlavors(flavors);
        return R.success(dish);
    }

    /**
     * 修改菜品信息
     */
    @Transactional
    @Override
    public R updateDish(DishDto dto) {
        //1.判断数据是否存在异常
        if (dto == null) {
            R.error("该数据存在异常");
        }

        //2.修改菜品信息
        dishMapper.updateById(dto);

        //3.修改口味
        //3.1先删后增，根据菜品id删除口味信息
        LambdaUpdateWrapper<DishFlavor> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(DishFlavor::getDishId, dto.getId());
        dishFlavorMapper.delete(wrapper);

        //4.新增口味
        List<DishFlavor> flavors = dto.getFlavors();

        //5.补全参数
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dto.getId());
        }
        dishFlavorMapper.insertFlavor(flavors);

        return R.success("修改成功");
    }

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public R pageInfo(Integer page, Integer pageSize, String name) {
        //1.返回的数据有一个分类名称
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        //添加查询条件
        if (name != null && name != "") {
            wrapper.like(Dish::getName, name);
        }
        wrapper.orderByDesc(Dish::getUpdateTime);

        //2.包含一个条件查询
        Page<Dish> pageInfo = new Page(page, pageSize);

        Page<Dish> page1 = dishMapper.selectPage(pageInfo, wrapper);

        //3.循环查询所有菜品，然后根据菜品的分类id查询出菜品名字
        List<Dish> records = page1.getRecords();
        ArrayList<DishDto> dtos = new ArrayList<>();
        for (Dish dish : records) {
            Long categoryId = dish.getCategoryId();
            Category category = categoryMapper.selectById(categoryId);
            //进行属性迁移
            DishDto dto = new DishDto();
            //把dish中的属性赋值给dto，依靠的是属性名一样
//            if(category!=null) {
            BeanUtils.copyProperties(dish, dto);
            dto.setCategoryName(category.getName());
            dtos.add(dto);
//            }
        }
        //4.把dtos封装到一个page对象中
        Page newPage = new Page<>();
        BeanUtils.copyProperties(page1, newPage);
        newPage.setRecords(dtos);

        return R.success(newPage);
    }

    /**
     * 批量和单独修改菜品状态
     *
     * @param status
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public void statusAll(Integer status, List<Long> ids) {
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(ids != null, Dish::getId, ids);
        List<Dish> list = this.list(wrapper);
        for (Dish dish : list) {
            if (dish != null) {
                dish.setStatus(status);
                this.updateById(dish);
            }
        }
    }

    /**
     * 批量和单独删除
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public R deleteAll(List<Long> ids) {
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(ids != null, Dish::getId, ids);
        List<Dish> list = this.list(wrapper);
        for (Dish dish : list) {
            //判断该菜品是否起售
            if (dish.getStatus() == 0) {
                //停售状态才能删除
                this.removeById(dish.getId());
                //获取菜品信息中的口味
                LambdaQueryWrapper<DishFlavor> newWrapper = new LambdaQueryWrapper<>();
                newWrapper.eq(DishFlavor::getDishId, dish.getId());
                dishFlavorService.remove(newWrapper);
            } else {
                throw new CustomException("该菜品还在售卖，无法删除");
            }
        }
        return R.error("该菜品还在售卖，无法删除");
    }


}
